﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CmccTool.Services
{
    internal static class DataGridViewRowExtensions
    {
        // 安全获取字符串
        public static string SafeGetString(this DataGridViewRow row, string columnName)
        {
            if (row == null || row.DataGridView == null)
                return string.Empty;

            // 检查列是否存在
            if (row.DataGridView.Columns.Contains(columnName))
            {
                var cellValue = row.Cells[columnName].Value;
                // 处理空值
                if (cellValue == null || cellValue == DBNull.Value)
                    return string.Empty;

                // 转换为字符串
                return Convert.ToString(cellValue, CultureInfo.InvariantCulture) ?? string.Empty;
            }
            return string.Empty;
        }

        // 安全获取整数
        public static int SafeGetInt(this DataGridViewRow row, string columnName)
        {
            string stringValue = row.SafeGetString(columnName);
            return int.TryParse(stringValue, out int result) ? result : 0;
        }

        // 安全获取双精度浮点数
        public static double SafeGetDouble(this DataGridViewRow row, string columnName)
        {
            string stringValue = row.SafeGetString(columnName);
            return double.TryParse(stringValue, out double result) ? result : 0.0;
        }

        // 安全获取日期时间（扩展功能）
        public static DateTime SafeGetDateTime(this DataGridViewRow row, string columnName)
        {
            string stringValue = row.SafeGetString(columnName);
            return DateTime.TryParse(stringValue, out DateTime result) ? result : DateTime.MinValue;
        }

        // 安全获取布尔值（扩展功能）
        public static bool SafeGetBool(this DataGridViewRow row, string columnName)
        {
            string stringValue = row.SafeGetString(columnName);
            return bool.TryParse(stringValue, out bool result) && result;
        }
    }
}
